package gz.smx.tools;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MyBatisTool {
    /**
     * 不带自动提交功能，一般用于数据的查询
     * @return
     * @throws Exception
     */
    public static SqlSession getSqlSession() throws Exception {
        //1. 读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        //2. 获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 3. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        return sqlSession;

    }

    /**
     * 带自动提交功能，一般用于数据的添加、修改和删除
     * @return SqlSession
     * @throws Exception
     */
    public static SqlSession getSqlSessionAndAutoCommit() throws Exception {
        //1. 读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        //2. 获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 3. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        return sqlSession;

    }
}
